import axios from "axios";
import qs from "qs";
import { apiBaseHost } from "@/common/env";
import eventHub from "@/common/eventHub";
import { fun } from "@/common/index";
import { ls } from "@/common/ls";

export const getAccessToken = () => ls.get("access_token");

// 创建实例时设置配置的默认值
const instance = axios.create({
  baseURL: apiBaseHost
});

// 在实例已创建后修改默认值
//instance.defaults.headers.common["token"] = getAccessToken();
// instance.defaults.headers.post["Content-Type"] = "application/x-www-form-urlencoded";

instance.interceptors.request.use(
  function(config) {
    //公共token
    config.headers.token = getAccessToken();
    config.data = qs.stringify(config.data);
    return config;
  },
  function(error) {
    // 对请求错误做些什么
    return Promise.reject(error);
  }
);

const allowErrorCodes = [0, 66001];

instance.interceptors.response.use(
  function(response) {
    if (eventHub.loadingInstance) {
      eventHub.loadingInstance.close();
    }
    if (response.status !== 200) {
      return Promise.reject(Error("服务器去旅行了"));
    }
    const { errorCode = 0, msg = "" } = response.data;
    if (!allowErrorCodes.includes(errorCode)) {
      return Promise.reject(Error(msg));
    }
    // if (errorCode === 66001) {
    //   location.href = "/login";
    //   throw Error("require login");
    // }

    return Promise.resolve(response.data);
  },
  function(error) {
    // 对请求错误做些什么
    return Promise.reject(error);
  }
);

export const request = (reqConfig: {
  url: string;
  data?: object;
  options?: any;
  method?: any;
}) => {
  const { url, data, options = {}, method = "post" } = reqConfig;
  if (options.tip) {
    eventHub.loadingInstance = fun.loading(options.tip);
  }
  return instance.request({
    url,
    data,
    method
  });
};
